package com.dfiles.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

/**
 * 水平滚动ListView
 * 
 */
public class HListView extends HorizontalScrollView implements OnClickListener {
	private LinearLayout mContainer;
	private ListAdapter mAdapter;
	private int mCurrentPosition = -1;
	private OnItemClickListener mOnItemClickListener;

	public HListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContainer = new LinearLayout(context);
		mContainer.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
		mContainer.setOrientation(LinearLayout.HORIZONTAL);
		mContainer.setGravity(Gravity.CENTER_VERTICAL);
		super.addView(mContainer);
	}

	@Override
	public void onClick(View v) {
		if (mOnItemClickListener != null) {
			View view = getSelectedView();
			mCurrentPosition = (Integer) v.getTag();
			mOnItemClickListener.onItemClick(mAdapter, view, v, mCurrentPosition);
		}
	}

	public ListAdapter getAdapter() {
		return mAdapter;
	}

	/**
	 * 
	 * @param adapter
	 *            null则清空列表
	 */
	public void setAdapter(ListAdapter adapter) {
		mAdapter = adapter;
		mContainer.removeAllViews();
		if (adapter == null)
			return;
		for (int i = 0; i < adapter.getCount(); i++) {
			View view = adapter.getView(i, null, null);
			view.setTag(i);
			view.setOnClickListener(this);
			mContainer.addView(view);
		}
	}

	public View getSelectedView() {
		if (mCurrentPosition < 0 || mCurrentPosition > mContainer.getChildCount()) {
			return null;
		}
		return mContainer.getChildAt(mCurrentPosition);
	}

	/**
	 * 将调用onItemClick事件
	 * 
	 * @param position
	 */
	public void setSelection(int position) {
		View view = getSelectedView();
		mCurrentPosition = position;
		if (mOnItemClickListener != null && position > -1 && position < mContainer.getChildCount()) {
			mOnItemClickListener.onItemClick(mAdapter, view, getSelectedView(), position);
		}
	}

	/**
	 * 获得当前选中的位置
	 * 
	 * @return
	 */
	public int getSelection() {
		return mCurrentPosition;
	}

	public void setOnItemClickListener(OnItemClickListener listener) {
		mOnItemClickListener = listener;
	}

	public interface OnItemClickListener {
		void onItemClick(ListAdapter adapter, View lastView, View view, int position);
	}

}
